<?php
/**
 * lzp300 
 */
class order extends actionAbstract {


    /**
     * 构造函数
     * @var array
     */
    function __construct() {
        parent::__construct();
        $this->partnerInfo = $this->userinfo=acl::checkLogin('PmsCookie','/index.php/partner/common/login');
        if($this->partnerInfo['parentid']!=0){
        	$this->partnerInfo['id'] = $this->partnerInfo['parentid'];
        }
    }
    
    //本酒店信息
    function hotelziduan($ziduan){
        $this->loadModel('hotel', 'category');
        $re=$this->hotel->categoryModel->fetchRow("select $ziduan from hotel_category where id=".(isset($_SESSION['hotel_id'])?$_SESSION['hotel_id']:0)." and partnerid=".$this->partnerInfo['id']);
    	if($re){
        	return $re[$ziduan];
        }else{
        	return 0;
        }
    }
	
    //待处理订单
    function processed(){
        $leftpost="order";
        $leftbot="processed";
    	$this->loadHelper('js');
        $js=new js();
        $str_return = $this->my_authority("order/processed");
        if(!$str_return){
        	$js->alert("您没有该权限！");exit();
        }
        global $pmsconfigs;
        $where="a.status IN(0,1)";
        $array=$this->all($where);
        $re=$array['re'];
        $pageHtml=$array['pageHtml'];
        $getall=$array['getall'];
        
        include $this->loadWidget('partnerTheme');
    }
	
	/**
     * 已入住订单
     */
    function todayCheck(){
        $leftpost="order";
        $leftbot="todayCheck";
        $this->loadHelper('js');
        $js=new js();
        $str_return = $this->my_authority("order/todayCheck");
        if(!$str_return){
        	$js->alert("您没有该权限！");exit();
        }
        global $pmsconfigs;
        $sta=strtotime(date('Y-m-d',time()));
        $where="a.status=4";
        $array=$this->all($where);
        $re=$array['re'];
        $getall=$array['getall'];
        $pageHtml=$array['pageHtml'];
        
        include $this->loadWidget('partnerTheme');
    }
	
    //待处理订单详细
    function detailsP(){
        global $pmsconfigs;
    	$this->loadHelper('js');
        $js=new js();
        $str_return = $this->my_authority("order/detailsP");
        if(!$str_return){
        	$js->alert("您没有该权限！");exit();
        }
        $leftpost="order";
        $this->loadModel('hotel','type');
        $this->loadModel('pms','orders');
        $this->loadModel('float','log');
        $this->loadModel('pms','channels');
        $hotelId=$this->hotelziduan('id');
        
        $act=isset($_GET['act'])?(int)($_GET['act']):0;
        $id=isset($_GET['id'])?(int)($_GET['id']):0;//订单id
        if($act){
            $leftbot="nowday";
        }else{
            $leftbot="processed";
        }
        
        //订单详情
        $resql="select a.*,b.title,b.bed,c.title as typeName from pms_orders as a left join hotel_type as b on b.id=a.roomId";
        $resql.=" left join pms_channels as c on c.osiiId=a.type where a.id=$id and a.hotelId=$hotelId";
        $re=$this->pms->ordersModel->fetchRow($resql);
        
        $types=$this->hotel->typeModel->fetchAll("select * from hotel_type where categoryid=$hotelId and status=1 AND parentTypeId != 0");

        include $this->loadWidget('partnerTheme');
    }
    
    //全部订单
    function total(){
        $leftpost="order";
        $leftbot="total";
        $this->loadHelper('js');
        $js=new js();
        $str_return = $this->my_authority("order/total");
        if(!$str_return){
        	$js->alert("您没有该权限！");exit();
        }
        $where="a.id>0";
        $array=$this->all($where);
        $re=$array['re'];
        $getall=$array['getall'];
        $pageHtml=$array['pageHtml'];
        
        $hotelId=$this->hotelziduan('id');
        $sql="";
        if($this->partnerInfo['isbusiness']==1){
            $sql="select * from hotel_type WHERE parentTypeId != 0 and categoryid=$hotelId";
        }else{
            $sql="select * from hotel_type WHERE parentTypeId != 0 and categoryid=$hotelId and (zisort=1 or zisort=2)";
        }
        
        $this->loadModel('hotel','type');
        $this->loadModel('pms','channels');
        $types=$this->hotel->typeModel->fetchAll($sql);
        $qudaos=$this->pms->channelsModel->fetchAll("select * from pms_channels");
        global $pmsconfigs;
        
        include $this->loadWidget('partnerTheme');
    }
    //订单详情  不用操作
    function details(){
    	$this->loadHelper('js');
        $js=new js();
        $str_return = $this->my_authority("order/details");
        if(!$str_return){
        	$js->alert("您没有该权限！");exit();
        }
        global $pmsconfigs;
        $this->loadModel('hotel','type');
        $this->loadModel('pms','orders');
        $this->loadModel('pms','channels');
        $hotelId=$this->hotelziduan('id');
        
        $id=isset($_GET['id'])?(int)($_GET['id']):0;
        $sql="select a.*,b.title,b.bed,c.title as typeName from pms_orders as a left join hotel_type as b on b.id=a.roomId";
        $sql.=" left join pms_channels as c on c.osiiId=a.type where a.id=$id and a.hotelId=$hotelId";
        $re=$this->pms->ordersModel->fetchRow($sql);
        
        include $this->loadWidget('partnerTheme');
    }
    
    //订单公用
    public function all($where=""){
        $this->loadHelper('pager');
        $this->loadModel('hotel','category');
        $this->loadModel('hotel','type');
        $this->loadModel('pms','orders');
        $this->loadModel('pms','channels');
        
        $hotelId=$this->hotelziduan('id');
        $where.=" and a.hotelId=$hotelId";
        
        $page=isset($_GET['page'])?(int)($_GET['page']):1;
        $keyword=isset($_GET['keyword'])?$_GET['keyword']:'';
        $statime=isset($_GET['statime'])?strtotime($_GET['statime']):'';
        $endtime=isset($_GET['endtime'])?strtotime($_GET['endtime']):'';
        $infotype=isset($_GET['infotype'])?(int)($_GET['infotype']):0;
        $qudao=isset($_GET['qudao'])?(int)$_GET['qudao']:9999;
        $status=isset($_GET['status'])?(int)$_GET['status']:9999;
        $payType=isset($_GET['payType'])?$_GET['payType']:'';
        
        $size = 10;
        $offset = ($page - 1) * $size;
        
        if(!empty($keyword)){
            $where.=" and (a.orderId like'%".$keyword."%' or a.name like'%".$keyword."%' or a.mobile like'%".$keyword."%')";
        }
        if(!empty($statime)){
            $where.=" and a.startDate>='".$statime."'";
        }
        if(!empty($endtime)){
            $where.=" and a.endDate<='".$endtime."'";
        }
        if(!empty($infotype)){
            $where.=" and a.roomId=$infotype";
        }
        if($qudao>=0&&$qudao<9999){
            $where.=" and a.type=$qudao";
        }
        if($status>=0&&$status<9999){
            $where.=" and a.status=$status";
        }
        if(!empty($payType)){
            $where.=" and a.payType='".$payType."'";
        }
        
		$sql_select="select";
		$sql_from=" from pms_orders as a left join hotel_type as b on b.id=a.roomId left join pms_channels as c on c.osiiId=a.type";
		$sql_where=" where ".$where;
		$sql_order_by=" order by a.created desc";
		
		$field_reto=" count(a.id) as thcount";
        $reto=$this->pms->ordersModel->fetchRow($sql_select.$field_reto.$sql_from.$sql_where.$sql_order_by);
        
        $count=$reto['thcount'];
        $number = ceil( $count / $size );
        $extend = new pager();
        $pageHtml = $extend->outputadmin( $number, $page, "", "", $count, $size );
		
		$field_re=" a.*,b.title,b.bed,c.title as typeName";
        $re=$this->pms->ordersModel->fetchAll($sql_select.$field_re.$sql_from.$sql_where.$sql_order_by." limit $offset,$size");
        
        return $re=array("re"=>$re,"pageHtml"=>$pageHtml,"getall"=>$_GET);
    }
    
    //99取消订单 、 4办理入住 、3办理退房
    function ordersEdit(){
    	$this->loadHelper('extend');
    	$str_return = $this->my_authority("order/ordersEdit");
    	if(!$str_return){
    		exit(json_encode(array('state'=>0,'html'=>'没有该权限！')));
    	}
        $this->loadModel('pms','orders');
        $this->loadModel('hotel','type');
        $this->loadModel('hotel','countrooms');
        $this->loadModel('orders','log');
        $hotelId=$this->hotelziduan('id');
        if($_POST){
            $orderid=isset($_POST['id'])?(int)($_POST['id']):0;
            $type = isset($_POST['type'])?(int)($_POST['type']):0;
            $status=isset($_POST['status'])?(int)($_POST['status']):'';//变化后的订单状态
            $remark=isset($_POST['remark'])?$_POST['remark']:'';//取消订单的原因
            //查询订单
            $order=$this->pms->ordersModel->fetchRow("select * from pms_orders where id=$orderid and hotelId=$hotelId");
            if(!$order){
                exit(json_encode(array('state'=>0,'html'=>'该订单不存在！')));
            }
            //父房型ID
            $parentTypeId=$this->hotel->typeModel->fetchRow("select parentTypeId from hotel_type where categoryid=$hotelId and id=".$order['roomId']);
            
            //判断状态 / $data 修改订单信息  
            $this->loadApi('osiiHotel');
            $osiiHotel=new osiiHotel();
            $body['orderNum'] = $order['orderId'];   
            if($status==99){
                $data['status']=99;
                $data['remark']=$remark;
				$ordersLog['operationType']="取消订单";
            }elseif($status==4){
                $data['status']=4;
				$ordersLog['operationType']="办理入住";
            }elseif($status==3){
                $data['status']=3;
				$ordersLog['operationType']="办理退房";
            }elseif($status==2){
                $data['status']=2;
				$ordersLog['operationType']="确认无房";
				
                //确认无房
                $body['opt'] = 'CONFIRM_ROOM_FAILURE';
                if($order['type']==301){
                    $hotelStatus_osii = $osiiHotel->OptOrder($body);
                }else{
                    $arr['orderId'] = $order['orderId'];
                    $arr['orderStatus'] = 4;
                    $arr['interfaceConfirmNo'] = 0;
                    $arr['interFaceSendID'] = $order['id'];
                    $arr['hotelConfirmNo'] = 0;
                    $arr['sourceID'] = $order['type'];
                    $hotelStatus_osii = $osiiHotel->DomesticPushOrderStatus($arr);
                }
            }elseif($status==1){
                $data['status']=1;
				$ordersLog['operationType']="确认有房";
                //确认有房
                $body['opt'] = 'CONFIRM_ROOM_SUCCESS';
                if($order['type']==301){
					if((time()-$order['created'])>=1500){
						$data['status']=99;$data['protime']=time();
						$this->pms->ordersModel->update($data,"id=$orderid and hotelId=$hotelId");
						exit(json_encode(array('state'=>0,'html'=>'操作失败！该单已失效。')));
					}else{
						$hotelStatus_osii = $osiiHotel->OptOrder($body);
					}
                }else{
                    $arr['orderId'] = $order['orderId'];
                    $arr['orderStatus'] = 3;
                    $arr['interfaceConfirmNo'] = 0;
                    $arr['interFaceSendID'] = $order['id'];
                    $arr['hotelConfirmNo'] = 0;
                    $arr['sourceID'] = $order['type'];
                    $hotelStatus_osii = $osiiHotel->DomesticPushOrderStatus($arr);
                }
            }else{
                exit(json_encode(array('state'=>0,'html'=>'操作失败！')));
            }
            $data['protime']=time();
            $re=$this->pms->ordersModel->update($data,"id=$orderid and hotelId=$hotelId");
            
            if($re){
				$ordersLog_hotelName=$this->hotelziduan('hotelName');
				$ordersLog['operationName']=$this->partnerInfo['userName'];
				$ordersLog['hotelName']=$ordersLog_hotelName;
				$ordersLog['orderNum']=$order['orderId'];
				$this->orders->logModel->insert($ordersLog);
				
                //修改时间内的使用房间数
                if($status==99||$status==3){
                    $this->hotel->countroomsModel->update("alreadyRoom=alreadyRoom-".$order['countRoom'],"hotelId=$hotelId and typeId=".$parentTypeId['parentTypeId']." and created>=".$order['startDate']." and created<".$order['endDate']);
                }
                exit(json_encode(array('state'=>1,'html'=>'操作成功！')));
            }else{
                exit(json_encode(array('state'=>0,'html'=>'操作失败！')));
            }
        }
    }
	
    //查询房型  时间内的价格
    function selectPrice(){
    	$this->loadHelper('extend');
        $this->loadModel('hotel','price');
        $this->loadModel('hotel','type');
        $this->loadModel('float','log');
        $hotelId=$this->hotelziduan('id');
        
        $typeid=isset($_POST['typeid'])?(int)($_POST['typeid']):0;
        $sta=isset($_POST['sta'])?strtotime($_POST['sta']):0;
        $end=isset($_POST['end'])?strtotime($_POST['end']):0;
        
        if($end<$sta){
            exit(json_encode(array('state'=>0,'html'=>0)));
        }
        if($sta!=0&&$end!=0&&$typeid!=0){
            $rule=0;//底价
            $typePrice=$this->hotel->typeModel->fetchRow("select price,parentTypeId from hotel_type where id=$typeid and categoryid=$hotelId");
            if($typePrice){
                $rule=$typePrice['price'];
            }
            
            $marketPrice=0;//该时间段的总价
            
            //房型价格
            $day=($end-$sta)/24/3600;
            for($i=0;$i<$day;$i++){
                $times=$sta+$i*24*3600;
                $thispeice=$this->hotel->priceModel->fetchRow("select sellPrice from hotel_price where typeid=$typeid and times=$times and isdetailed=1 and hotelId=$hotelId");
                if($thispeice){
                    $marketPrice=$marketPrice+$thispeice['sellPrice'];
                }else{
                    $marketPrice=$marketPrice+$rule;
                }
            }
            
            //浮动价格
            $float_price_sql="select sellmoney,floating from float_log where hotelid=$hotelId and $end>time and $sta<=time and parent_TypeId=".$typePrice['parentTypeId'];
            $float_price=$this->float->logModel->fetchAll($float_price_sql);
            if($float_price){
                foreach($float_price as $k=>$v){
                    if($v['floating']==1){
                        $marketPrice=$marketPrice+$v['sellmoney'];
                    }else{
                        $marketPrice=$marketPrice-$v['sellmoney'];
                    }
                }
            }
            
            exit(json_encode(array('state'=>1,'html'=>$marketPrice)));
        }else{
            exit(json_encode(array('state'=>1,'html'=>0)));
        }
    }
	
    /**
	 *selectRooms 查看可用房间数    @typeid 子房型id    @$statime 入住时间-时间戳    @$endtime 离店时间-时间戳
	 */
    function selectRooms($typeid,$statime,$endtime){
        $availableRoom=0;//$availableRoom 返回可用房间数
        $this->loadModel('hotel','type');
        $this->loadModel('hotel','countrooms');
        $this->loadModel('hotel','typestatus');
        
        $hotelId=$this->hotelziduan('id');
        
        //查询父房型id
        $th_typeid_sql="select parentTypeId from hotel_type where categoryid=$hotelId and id=$typeid";
        $th_typeid=$this->hotel->typeModel->fetchRow($th_typeid_sql);
        
        if(!$th_typeid){
            return $availableRoom;exit;
        }
        
        //查询子房型房态
        $roomsql="select id from hotel_typestatus where hotelId=$hotelId and typeId=$typeid and status!=1 and parentTypeId=".$th_typeid['parentTypeId'];
        $roomsql.=" and times>=$statime and times<$endtime";
        $roomStatus=$this->hotel->typestatusModel->fetchRow($roomsql);
        if($roomStatus){
            return $availableRoom;exit;
        }
        
        //判断房型下的房间数是否足够
        $roomNum=$this->hotel->typeModel->fetchRow("select roomNum from hotel_type where id=".$th_typeid['parentTypeId']);
        if($roomNum){
            $availableRoom=$roomNum['roomNum'];
            
            $sql="select alreadyRoom from hotel_countrooms where hotelId=$hotelId and typeId=".$th_typeid['parentTypeId'];
            $sql.=" and created>=$statime and created<$endtime order by alreadyRoom desc";
            $infos=$this->hotel->countroomsModel->fetchRow($sql);
            if($infos){
                $availableRoom=$roomNum['roomNum']-$infos['alreadyRoom'];
            }
        }
        
        return $availableRoom;
    }
    /**
     * lockRoomstaus 锁定房间    @$typeid 房型id    @$statime 入住时间戳    @$endtime 离店时间戳    @$infos 房间id数组
     * @$countRooms 入住房间数    @$orderid 订单id    @$status 房态(如：1[空闲中]等等...)
     */
    function lockRoomstaus($typeid,$statime,$endtime,$countRooms){
        //$alreadyRoom 已用房间数
        $this->loadModel('hotel','type');
        $this->loadModel('hotel','countrooms');
        
        $hotelId=$this->hotelziduan('id');
        
        $th_typeid_sql="select parentTypeId from hotel_type where categoryid=$hotelId and id=$typeid";
        $th_typeid=$this->hotel->typeModel->fetchRow($th_typeid_sql);
        $typeid=$th_typeid['parentTypeId'];
        
        $allRoom=$this->hotel->typeModel->fetchRow("select roomNum from hotel_type where id=$typeid");
        
        $day=($endtime-$statime)/3600/24;
        for($i=0;$i<$day;$i++){
            $intimes=$statime+$i*24*3600;
            $sql="select id from hotel_countrooms where hotelId=$hotelId and typeId=$typeid and created=$intimes";
            $lookRoom=$this->hotel->countroomsModel->fetchRow($sql);
            if($lookRoom){
                $this->hotel->countroomsModel->update("alreadyRoom=alreadyRoom+$countRooms","hotelId=$hotelId and typeId=$typeid and created=$intimes");
            }else{
                $data['hotelId']=$hotelId;
                $data['typeId']=$typeid;
                $data['created']=$intimes;
                $data['alreadyRoom']=$countRooms;
                $this->hotel->countroomsModel->insert($data);
            }
        }
    }
    
    //ajax改变订单状态
    function ajaxSetOrder(){
        $orderid = $_POST['id'];
        $this->loadHelper('extend');
        $this->loadModel('pms','orders');
        $this->loadModel('sys','finance');
        $hotelId=$this->hotelziduan('id');
        
        $order = $this->pms->ordersModel->fetchRow('SELECT a.*,b.title FROM pms_orders as a LEFT JOIN pms_channels as b ON a.type=b.osiiId WHERE a.id='.$orderid);
        
        if($hotelId != $order['hotelId']){
            ajaxReturn ('','此订单不是你的订单，不能退订！', 0 );exit;
        }
        if($order['title'] != '去哪儿'){
            ajaxReturn ('','此订单不是去哪儿的订单，不能退订！', 0 );exit;
        }
        if($order['status']>1){
            ajaxReturn ('','此订单已完成入住，不能退订！', 0 );exit;
        }
        
        $re=$this->sys->financeModel->fetchRow("select getPrice from sys_finance where orderId='".$order['orderId']."' and hotelId='".$order['hotelId']."' and typeId='".$order['roomId']."' and sourceId='".$order['type']."'");
        
        //退订订单
        $this->loadApi('osiiHotel');
        $osiiHotel=new osiiHotel();
        $body['orderNum'] = $order['orderId'];
        $body['opt'] = 'APPLY_UNSUBSCRIBE';
        $body['arrangeType'] = '';
        $body['confirmationNumber'] = '';
        $body['money'] = !empty($re)?$re['getPrice']:$order['price'];
        $body['remark'] = '';
        $body['faxSendPartnerName'] = '';
        $body['faxStamp'] = '';
        $body['faxReceiveName'] = '';
        $body['faxReceiveFaxNumber'] = '';
        $body['faxSender'] = '';
        $body['faxSenderTelNumber'] = '';
        $body['faxReceiver'] = '';
        $body['faxReceiverTelNumber'] = '';
        $body['faxSendType'] = '';
        $body['prices'] = '';
        $body['roomChargeSettlement'] = '';
        $body['otherChargeSettlement'] = '';
        $body['smsContent'] = '';
        
        $hotelStatus_osii = $osiiHotel->OptOrder($body);
        
        if (is_array($hotelStatus_osii['return']) && !empty($hotelStatus_osii['return']['body']['errCode'])) {
            ajaxReturn ('','退订订单失败！', 0 );exit;
        }else{
            $this->pms->ordersModel->update('status=5','id='.$orderid);
            ajaxReturn ('','退订订单申请成功，去哪儿网正在审核中！', 1 );exit;
        }
    }
    
}